﻿namespace WebMarkupMin.WebForms.Pages
{
	using System;
	using System.IO;
	using System.Web;
	using System.Web.UI;

	using Core;
	using Web;
	using Web.Helpers;

	/// <summary>
	/// Web Forms page with support of GZIP/Deflate compression
	/// </summary>
    public class CompressedPage : Page
    {
		/// <summary>
		/// Flag for whether to enable GZIP/Deflate compression of content
		/// </summary>
		private bool _enableCompression = true;
		private bool _enableCompressionSet;

		/// <summary>
		/// Gets or sets a flag for whether to enable GZIP/Deflate compression of content
		/// </summary>
		public bool EnableCompression
		{
			get
			{
				if (!_enableCompressionSet)
				{
					return WebMarkupMinContext.Current.IsCompressionEnabled();
				}

				return _enableCompression;
			}
			set
			{
				_enableCompression = value;
				_enableCompressionSet = true;
			}
		}


		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			if (!EnableCompression)
			{
				return;
			}

			HttpContext context = HttpContext.Current;
			HttpRequest request = context.Request;
			HttpResponse response = context.Response;

			if (response.StatusCode == 200 && CompressionHelper.IsCompressionSupported(request))
			{
				context.Items["originalResponseFilter"] = response.Filter;
				CompressionHelper.TryCompressContent(context);
			}
		}

		protected override void OnError(EventArgs e)
		{
			base.OnError(e);

			HttpContext context = HttpContext.Current;
			if (context.Items.Contains("originalResponseFilter"))
			{
				var originalResponseFilter = context.Items["originalResponseFilter"] as Stream;
				if (originalResponseFilter != null)
				{
					context.Response.Filter = originalResponseFilter;
				}
			}
		}
    }
}